package com.haoshuang.zhouzhoubang.utils

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.net.http.SslError
import android.util.Log
import android.webkit.SslErrorHandler
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.ActivityUtils
import com.haoshuang.zhouzhoubang.ui.activity.VideoActivity
import com.haoshuang.zhouzhoubang.ui.page.study.detail.TrainDetailsActivity
import com.mufeng.libs.utils.startPage
import java.io.InputStream

object WebSettingsUtils {

    @SuppressLint("SetJavaScriptEnabled")
    fun setWebSettings(context: Context, webView: WebView) {
        val settings = webView.settings

        // 存储(storage)
        // 启用HTML5 DOM storage API，默认值 false
        settings.domStorageEnabled = true
        // 启用Web SQL Database API，这个设置会影响同一进程内的所有WebView，默认值 false
        // 此API已不推荐使用，参考：https://www.w3.org/TR/webdatabase/
        settings.databaseEnabled = true

        // 定位(location)
        settings.setGeolocationEnabled(true)

        // 是否保存表单数据
        settings.saveFormData = true
        // 是否当webview调用requestFocus时为页面的某个元素设置焦点，默认值 true
        settings.setNeedInitialFocus(true)

        // 是否支持viewport属性，默认值 false
        // 页面通过`<meta name="viewport" ... />`自适应手机屏幕
        settings.useWideViewPort = true
        // 是否使用overview mode加载页面，默认值 false
        // 当页面宽度大于WebView宽度时，缩小使页面宽度等于WebView宽度
        settings.loadWithOverviewMode = true
        // 布局算法
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL

        // 是否支持Javascript，默认值false
        settings.javaScriptEnabled = true
        // 是否支持多窗口，默认值false
        settings.setSupportMultipleWindows(true)
        // 是否可用Javascript(window.open)打开窗口，默认值 false
        settings.javaScriptCanOpenWindowsAutomatically = true
        // 资源访问
        settings.allowContentAccess = true // 是否可访问Content Provider的资源，默认值 true
        settings.allowFileAccess = true    // 是否可访问本地文件，默认值 true
        // 资源加载
        settings.loadsImagesAutomatically = true // 是否自动加载图片
        settings.blockNetworkImage = false       // 禁止加载网络图片
        settings.blockNetworkLoads = false       // 禁止加载所有网络资源

        // 缩放(zoom)
        settings.setSupportZoom(true)          // 是否支持缩放
        settings.builtInZoomControls = false // 是否使用内置缩放机制
        settings.displayZoomControls = true  // 是否显示内置缩放控件

        // 默认文本编码，默认值 "UTF-8"
        settings.defaultTextEncodingName = "UTF-8"
        settings.defaultFontSize = 16   // 默认文字尺寸，默认值16，取值范围1-72
        settings.defaultFixedFontSize = 16   // 默认等宽字体尺寸，默认值16
        settings.minimumFontSize = 8    // 最小文字尺寸，默认值 8
        settings.minimumLogicalFontSize = 8 // 最小文字逻辑尺寸，默认值 8
        settings.textZoom = 100              // 文字缩放百分比，默认值 100
        settings.useWideViewPort = true
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        // 用户是否需要通过手势播放媒体(不会自动播放)，默认值 true
        settings.mediaPlaybackRequiresUserGesture = true
        // 5.0以上允许加载http和https混合的页面(5.0以下默认允许，5.0+默认禁止)
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        // 是否在离开屏幕时光栅化(会增加内存消耗)，默认值 false
        settings.offscreenPreRaster = false
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
        settings.pluginState = WebSettings.PluginState.ON
        webView.webViewClient = object : WebViewClient() {
            var url = ""
            var jumpVideo = false
            @SuppressLint("WebViewClientOnReceivedSslError")
            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler?,
                error: SslError?
            ) {
                //super.onReceivedSslError(view, handler, error)
                handler?.proceed()
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
                Log.d("WebSettingUtils", errorResponse.toString());
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                this.url = url!!
            }

            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                val url = request?.url?.path ?: return false
                Log.e("shouldOverrideUrlLoading", url)
                view?.loadUrl(url)
                return true
            }

            override fun shouldInterceptRequest(
                view: WebView?,
                request: WebResourceRequest?
            ): WebResourceResponse? {
                val url = request?.url
                Log.e("shouldInterceptRequest", url.toString())
                if (url.toString().contains(".mp4")){
                    if (!jumpVideo) {
                        jumpVideo = true
                        ActivityUtils.getTopActivity()
                            .startPage<VideoActivity>("url" to url.toString())
                    }
                    ActivityUtils.finishActivity(TrainDetailsActivity::class.java)
                    return null
                }
                return super.shouldInterceptRequest(view, request)
            }
        }
    }

}